package model.base;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;

public class SolutionManager {

	private HashMap<String, Solution> solutionMap;
	private static SolutionManager instance = null;
	private static final String FILE_NAME = "solutions.dat";
	
	protected SolutionManager(){
		solutionMap = new HashMap<String, Solution>();
	}
	
	public static SolutionManager getInstance(){
		if (instance == null)
			instance = new SolutionManager();
		return instance;
		}

	public void addSolution(Solution solution){
		solutionMap.put(solution.getTheProblem(), solution);
	}
	
	public Solution getSolution(String theProblem){
		return solutionMap.get(theProblem);
	}
	
	public void saveSolutionsToFile(){
		try{
			File writingTo = new File(FILE_NAME);
			FileOutputStream fos = new FileOutputStream(writingTo);	
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(solutionMap);
			oos.flush();
			oos.close();
			fos.close();			
		} catch(Exception e){}
	}
	
	@SuppressWarnings("unchecked")
	public void loadSolutionsFromFile(){
		try{
			File toRead = new File(FILE_NAME);
			FileInputStream fis = new FileInputStream(toRead);
			ObjectInputStream ois = new ObjectInputStream(fis);
			solutionMap = (HashMap<String, Solution>)ois.readObject();
			ois.close();
			fis.close();
		}catch (Exception e){}
	}
	
	public boolean checkSolutionMap(String theProblem){
		return solutionMap.containsKey(theProblem);
	}
}